<template>
  <div class="app-container org">
    <el-card class="leftCard">
      <!-- 搜索条件盒子 -->
      <el-row>
        <el-col :span="15">
          <p class="pinformation">搜索条件</p>
        </el-col>
      </el-row>

      <el-row>
        <el-form :model="queryParams" ref="queryRef" label-width="80">
          <el-row>
            <el-col :span="12">
              <el-form-item label="药品名称：" prop="drugName">
                <el-input clearable maxlength="100" v-model="queryParams.drugName" placeholder="请输入药品名称"
                  @keyup.enter="handleQuery" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="质量等级：" prop="qualityLevel" label-width="75">
                <el-select placeholder="请选择" clearable v-model="queryParams.qualityLevel" filterable>
                  <el-option v-for="dict in proxy.addListNoLimit(sys_drug_quality_level)" :key="dict.value"
                    :label="dict.label" :value="parseInt(dict.value)" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="类型：" prop="drugType">
                <el-select placeholder="请选择" clearable v-model="queryParams.drugType" filterable>
                  <el-option v-for="dict in proxy.addListNoLimit(sys_drug_type)" :key="dict.value" :label="dict.label"
                    :value="parseInt(dict.value)" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-row justify="center">
                <el-button type="success" @click="handleQuery">搜索</el-button>
                <el-button class="resetBtn" @click="resetQuery">重置</el-button>
              </el-row>
            </el-col>
          </el-row>
        </el-form>
      </el-row>
      <div>
        <el-row>
          <p class="pinformation">化学药品列表</p>
          <p class="totalStyle">共 {{ total }} 条数据</p>
        </el-row>
        <el-table ref="mainTableRef" class="business" v-loading="loading" :data="usageTable"
          :row-class-name="tableRowClass" @row-click="rowClick" @selection-change="handleSelectionChange">
          <el-table-column label="药品名称" align="center" prop="drug.drugName" />
          <el-table-column label="质量等级" align="center" prop="drug.qualityLevel">
            <template #default="scope">
              <dict-tag :options="sys_drug_quality_level" :value="scope.row.drug.qualityLevel" />
            </template>
          </el-table-column>
          <el-table-column label="类型" align="center" prop="drug.drugType">
            <template #default="scope">
              <dict-tag :options="sys_drug_type" :value="scope.row.drug.drugType" />
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize" @pagination="getList" />
      </div>
    </el-card>

    <el-card class="rightCard">
      <!-- 搜索条件区域 -->
      <el-row>
        <el-col :span="8">
          <el-form-item label="化学药品名称：" prop="bzwzName">
            {{ searchOutinForm.drugName }}
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="质量等级：" prop="qualityLevel">
            <dict-tag :options="sys_drug_quality_level" :value="searchOutinForm.qualityLevel" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="2">
          <p class="pinformation">搜索条件</p>
        </el-col>
      </el-row>
      <el-form label-width="120px" :model="searchOutinForm" ref="searchOutinRef">
        <el-row>
          <el-col :span="6">
            <el-form-item label="备案证明编号：" prop="code">
              <el-input clearable maxlength="100" placeholder="请选择" v-model="searchOutinForm.code"
                @keyup.enter="getcheckListLedger" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="销售单位：" prop="saleFactory" label-width="85">
              <el-input clearable maxlength="100" placeholder="请输入销售单位" v-model="searchOutinForm.saleFactory"
                @keyup.enter="getcheckListLedger" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="入库日期：" label-width="85">
              <el-date-picker v-model="dateRange1" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
                start-placeholder="开始日期" end-placeholder="结束日期" />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="使用日期：" label-width="85">
              <el-date-picker v-model="dateRange2" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
                start-placeholder="开始日期" end-placeholder="结束日期" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <!-- 字段 -->
            <el-form-item label="领用人：" prop="createUserId">
              <el-select v-model="searchOutinForm.createUserId" filterable clearable>
                <el-option v-for="item in proxy.addListNoLimit(
                  userList,
                  'userId',
                  'nickName'
                )" :value="item.userId" :key="item.userId" :label="item.nickName"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="保管人：" prop="drugAdminOneId" label-width="85">
              <el-select v-model="searchOutinForm.drugAdminOneId" filterable clearable>
                <el-option v-for="item in proxy.addListNoLimit(
                  userList,
                  'userId',
                  'nickName'
                )" :value="item.userId" :key="item.userId" :label="item.nickName"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="状态：" prop="stepId" label-width="85">
              <el-select placeholder="请选择" clearable v-model="searchOutinForm.stepId" filterable>
                <el-option v-for="dict in proxy.addListNoLimit(sys_drug_step)" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-row justify="end">
              <el-button type="success" @click="getcheckListLedger">搜索</el-button>
              <el-button class="resetBtn" @click="resetBtn">重置</el-button>
            </el-row>
          </el-col>
        </el-row>
      </el-form>
      <!-- /搜索条件区域 -->

      <!-- 技术指标表格 -->
      <el-row>
        <p class="pinformation">化学药品列表</p>
        <p class="totalStyle">共 {{ OtinTotal }} 条数据</p>
        <el-row style="padding-bottom: 5px; margin-left: 20px">
          <el-button link icon="Plus" @click="addOtin">新增</el-button>
        </el-row>
      </el-row>

      <el-table ref="sub1TableRef" class="business" v-loading="targetTableLoading" :data="targetList"
        @selection-change="outSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" type="index" width="70" align="center" />
        <el-table-column label="日期" align="center" prop="useDate" />
        <el-table-column label="备案证明编号" align="center" prop="drugOut.drug.code" />
        <el-table-column label="领用量" align="center" prop="drugOut.outCount" />
        <el-table-column label="使用量" align="center" prop="drugOut.useCount" />
        <el-table-column label="剩余量" align="center" prop="drugOut.remainCount" />
        <el-table-column label="剩余是否入库" align="center" />
        <el-table-column label="使用人" align="center" prop="createUserId">
          <template #default="scope">
            {{
              proxy.getItemByArray(
                userList,
                "userId",
                scope.row.createUserId,
                "nickName"
              )
            }}
          </template>
        </el-table-column>
        <el-table-column label="监督人" align="center" prop="createSupId">
          <template #default="scope">
            {{
              proxy.getItemByArray(
                userList,
                "userId",
                scope.row.createSupId,
                "nickName"
              )
            }}
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="stepId">
          <template #default="scope">
            <dict-tag :options="sys_drug_step" :value="scope.row.stepId" />
          </template>
        </el-table-column>
      </el-table>
      <!-- /技术指标表格 -->
      <pagination v-show="OtinTotal > 0" :total="OtinTotal" v-model:page="searchOutinForm.pageNum"
        v-model:limit="searchOutinForm.pageSize" />
      <!-- @pagination="" -->
    </el-card>

    <el-dialog :class="'el-dialog-theme3'" append-to-body draggable :close-on-click-modal="false"
      v-model="otinOpen" :title="otinTitle">
      <!-- @close="closedInDialog" -->
      <el-form label-width="110" ref="otinRef" :model="form" :rules="rules">
        <el-row>
          <el-col :span="8">
            <el-form-item label="药品类型：" prop="drug.drugType">
              <dict-tag :options="sys_drug_type" :value="form.drug.drugType" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="药品名称：" prop="drug.drugName">
              {{ form.drug.drugName }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="质量等级：" prop="drug.qualityLevel">
              <dict-tag :options="sys_drug_quality_level" :value="form.drug.qualityLevel" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="备案证明编号：" prop="code">
              {{ form.drug.code }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="使用用途：" prop="remark">
              <el-input clearable maxlength="100" v-model="form.remark"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="用前剩余量：" prop="outCount">
              {{ form.remainCount }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="本次使用量：" prop="useCount">
              <el-input-number clearable v-model="form.useCount" @change="useCountChange" :min="0"
                controls-position="right" style="width: 100%"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="用后剩余量：" prop="drug.produceFactory">
              {{ form.remainCount1 }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="剩余是否入库：" prop="isLike">
              <el-radio v-model="form.isLike" :label="1">是</el-radio>
              <el-radio v-model="form.isLike" :label="0">否</el-radio>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="监督人：" prop="createSupId">
              <el-select v-model="form.createSupId" filterable clearable>
                <el-option v-for="item in userList" :value="item.userId" :key="item.userId"
                  :label="item.nickName"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="5">
            <el-form-item label="使用人：" prop="createUserId">
              {{
                proxy.getItemByArray(
                  userList,
                  "userId",
                  form.createUserId,
                  "nickName"
                )
              }}
            </el-form-item>
          </el-col> -->
          <!-- <el-col :span="3" style="padding-top: 5px">
            <el-button size="small" type="success">签字</el-button>
          </el-col> -->
          <el-col :span="8">
            <el-form-item label="使用日期：" prop="useDate">
              <el-date-picker v-model="form.useDate" placeholder="请选择使用日期" type="date" value-format="YYYY-MM-DD" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="save">保 存</el-button>
          <el-button type="danger" @click="otinOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Instrument">
import { delLedger } from "@/api/resource/ledger";
import { listUser } from "@/api/contract/check";
import {
  listUseList,
  FormLedger,
  checkListLedger,
  addHxypUsage,
} from "@/api/resource/hxyp";
import { getCurrentTime } from "@/api/common";

const { proxy } = getCurrentInstance();

const { sys_drug_type, sys_drug_quality_level, sys_drug_step } = proxy.useDict(
  "sys_drug_type",
  "sys_drug_quality_level",
  "sys_drug_step"
);

const loading = ref(false);
const ids = ref([]);
const total = ref(0);
const usageTable = ref([]);
const targetTableLoading = ref(false);
const dateRange = ref([]);
const dateRange1 = ref([]);
const dateRange2 = ref([]);
const otinOpen = ref(false);
const otinTitle = ref("新增化学药品使用记录");
const searchOutinForm = ref({
  pageNum: 1,
  pageSize: 10,
});
onMounted(() => {
  nextTick(() => {
    getTableHeight();
    window.addEventListener("resize", getTableHeight);
  })
})
onUpdated(() => {
  nextTick(function () {
    getTableHeight();
  });

  getList();
});

onBeforeUnmount(() => {
  window.removeEventListener("resize", getTableHeight);
});

watch(
  () => total.value,
  () => {
    if (total.value) {
      heightParams.value = [
        { tableName: "main", bottomHeight: 73 },
        { tableName: "sub1", bottomHeight: 73 },
      ];
    } else {
      heightParams.value = [
        { tableName: "main", bottomHeight: 21 },
        { tableName: "sub1", bottomHeight: 73 },
      ];
    }
    getTableHeight();
  }
);

const heightParams = ref([
  { tableName: "main", bottomHeight: 21 },
  { tableName: "sub1", bottomHeight: 73 },
]);

function getTableHeight() {
  proxy.adaptiveHeight(proxy, heightParams.value);
}

const data = reactive({
  form: { drug: {}, drugOut: {}, isLike: 0 },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    qualityLevel: -1,
    drugType: -1,
    createUserId: -1,
    drugAdminOneId: -1,
    stepId: -1,
  },
  rules: {
    useCount: [
      { required: true, message: "本次使用量不能为空", trigger: "blur" },
    ],
    createSupId: [
      { required: true, message: "监督人不能为空", trigger: "blur" },
    ],
    useDate: [{ required: true, message: "使用日期不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询仪器档案列表 */
function getList() {
  loading.value = true;
  let temp = {
    "drug.drugName": queryParams.value.drugName,
    "drug.qualityLevel": queryParams.value.qualityLevel,
    "drug.drugType": queryParams.value.drugType,
    pageSize: queryParams.value.pageSize,
    pageNum: queryParams.value.pageNum,
  };
  debugger;
  listUseList(proxy.addDateRange(temp, dateRange.value)).then((response) => {
    usageTable.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
// 表单重置
// function reset() {
//   form.value = {};
//   proxy.resetForm("");
// }

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
handleQuery();
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  dateRange.value = [];
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.instrumentId);
}

const outIds = ref([]);
function outSelectionChange(selection) {
  outIds.value = selection.map((item) => item.outinId);
}

const OtinTotal = ref(0);

const targetList = ref([]);

function resetBtn() {
  proxy.resetForm("searchOutinRef");
  dateRange1.value = [];
  dateRange2.value = [];
  getcheckListLedger();
}

function rowClick(row) {
  proxy.resetForm("searchOutinRef");
  dateRange1.value = [];
  dateRange2.value = [];
  FormLedger(row.outId).then((res) => {
    searchOutinForm.value.qualityLevel = res.data.drug.qualityLevel;
    searchOutinForm.value.drugName = res.data.drug.drugName;
    searchOutinForm.value.outId = row.outId;
    heightBright.value = row.outId;
    getcheckListLedger();
  });
}

function getcheckListLedger() {
  if (searchOutinForm.value.outId) {
    let temp = {
      "drug.code": searchOutinForm.value.code,
      "drug.saleFactory": searchOutinForm.value.saleFactory,
      "drug.drugAdminOneId": searchOutinForm.value.drugAdminOneId,
      "drugOut.createUserId": searchOutinForm.value.createUserId,
      stepId: searchOutinForm.value.stepId,
      outId: searchOutinForm.value.outId,
      pageSize: searchOutinForm.value.pageSize,
      pageNum: searchOutinForm.value.pageNum,
    };
    temp.params = {
      beginTime: dateRange1.value[0],
      endTime: dateRange1.value[1],
      beginTime1: dateRange2.value[0],
      endTime1: dateRange2.value[1],
    };
    checkListLedger(temp).then((res) => {
      targetList.value = res.rows;
      OtinTotal.value = res.total;
    });
  } else {
    proxy.$modal.msgError("请先选择要搜索的仪器设备");
  }
}

function delCheckClick(row) {
  proxy.$modal
    .confirm("是否确认删除该条记录？")
    .then(function () {
      delLedger(row.checkId).then((res) => {
        proxy.$modal.msgSuccess("删除成功");
        getcheckListLedger();
      });
    })
    .catch(() => { });
}

const heightBright = ref("");
function tableRowClass({ row }) {
  if (row) {
    if (row.outId == heightBright.value) {
      return "current-row";
    }
    return "";
  }
}

const userList = ref([]);
listUser().then((res) => {
  userList.value = res.data;
});

function addOtin() {
  if (searchOutinForm.value.outId) {
    FormLedger(searchOutinForm.value.outId).then((res) => {
      form.value = res.data;
      delete form.value.remark;
      delete form.value.useCount;
      delete form.value.createUserId;
      form.value.remainCount1 = form.value.remainCount;
      if (!form.value.isLike) {
        form.value.isLike = 0;
      }
      getCurrentTime().then((res1) => {
        form.value.useDate = res1.data;
      });
      otinOpen.value = true;
    });
  } else {
    proxy.$modal.msgError("请选择左侧化学药品");
  }
}

function save() {
  if (form.value.useCount !== 0) {
    proxy.$refs["otinRef"].validate((valid) => {
      if (valid) {
        addHxypUsage(form.value).then((res) => {
          otinOpen.value = false;
          proxy.$modal.msgSuccess("保存成功");
          getcheckListLedger();
        });
      }
    });
  } else {
    proxy.$modal.msgError("使用量不能为0");
  }
}

function useCountChange() {
  nextTick(() => {
    if (form.value.useCount > form.value.remainCount) {
      proxy.$modal.msgError(
        "本次使用量不可以超过剩余量,已更改为可以使用的最大量"
      );
      form.value.remainCount1 = 0;
      form.value.useCount = form.value.remainCount;
    } else {
      form.value.remainCount1 = form.value.remainCount - form.value.useCount;
    }
  });
}
</script>

<style lang="scss" scoped></style>
